package top.suven.base.http.Interceptor;//package com.suven.frame.server.Interceptor;


import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.suven.base.core.cat.dubbo.GlobalLogbackThread;
import top.suven.base.http.exception.BusinessLogicException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LogbackTraceIdHandlerInterceptor extends HandlerInterceptorAdapter {
	private static Logger logger = LoggerFactory.getLogger(LogbackTraceIdHandlerInterceptor.class);

    public LogbackTraceIdHandlerInterceptor(){}


	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BusinessLogicException {
		String module = "top/suven/base";
		try {
            request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE,Sets.newHashSet(MediaType.APPLICATION_JSON));
			module = request.getServletPath().split("/")[1];
		}catch (Exception e){}
		GlobalLogbackThread.initGlobalLogbackTraceId(module);

		logger.info("gc server global logback info logback_trace_id ");
		return true;

	}

	@Override
	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		GlobalLogbackThread.removeTraceId();
	}


}
